import { getUserInfoApi, loginApi } from "@/api/login";
import baseStorePinia from "@/store/modules/base";
export default function OperationHook(state: { formState: Login.LoginForm }) {
  const { formState } = state;
  const { setToken, setUserInfo, token } = baseStorePinia();

  const submitHandle = async () => {
    const { username, password } = formState;
    if (!username) {
      return uni.showToast({
        icon: "error",
        title: `请填写用户名`,
      });
    }
    if (!password) {
      return uni.showToast({
        icon: "error",
        title: `请填写密码!`,
      });
    }
    uni.showLoading({
      title: "登录中...",
    });
    return loginApi({ username, password, clientType: "MANAGE" })
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          uni.showToast({
            icon: "success",
            title: "登录成功!",
          });
          setToken(data);
          getUserInfo();
        }
      })
      .finally(() => {
        uni.hideLoading();
      });
  };
  // 获取用户信息
  const getUserInfo = async () => {
    return getUserInfoApi({ clientCode: "2" }).then((res: any) => {
      const { code, data } = res;
      console.log("getUserInfo", res);
      if (code === 200) {
        setUserInfo(data.user);
        uni.switchTab({
          url: "/pages/layout/waybill/index",
        });
      }
    });
  };
  return {
    submitHandle,
    getUserInfo,
    token,
  };
}
